<?php
namespace app\controller;

use app\BaseController;
use app\facade\Token;
use app\model\money\MoneyModel;
use app\model\money\TypeModel;
use app\model\money\SubtypeModel;

use app\validate\money\PostValidate;

class Money extends BaseController
{
    public function type() {
        return json(TypeModel::select());
    }
    public function subtype() {
        return json(SubtypeModel::select());
    }

    // 获取所有记录（按照时间倒过来排列
    public function record()
    {
        $type = input("get.type");
        $subtype = input("get.subtype");
        $model = MoneyModel::order("time","desc");
        if ($type != '*') $model=$model->where("type",$type);
        if ($subtype != '*') $model=$model->where("subtype",$subtype);
        return json($model->select());
    }

    // 获取一共有多少钱
    public function sum() {
        // 使用所有记录计算，保证结果正确
        $recoeds = MoneyModel::select();
        $sum = 0;
        for ($i=0; $i<count($recoeds); $i++) {
            $r = $recoeds[$i];
            if ($r['subtype'] == "IN") {
                $sum += $r['number'];
            } else {
                $sum -= $r['number'];
            }
        }
        return json(array(
            "sum"   => $sum,
        ));
    }

    // 新建记录
    public function post() {
        $content = input("post.content");
        $number = input("post.number")*100;
        $subtype = input("post.subtype");
        $type = input("post.type");
        $user = input("post.user");

        $V = new PostValidate();
        $data = [
            'content' => $content,
            'num'  => $number,
            'type'    => $type,
            'subtype' => $subtype,
            'user'  => $user,
        ];
        if (!$V->check($data)) {
            return json([
                'msg'=>$V->getError(),
            ]);
        }

        // 判断是否存在这个类型
        if (!SubtypeModel::isExist($subtype)) {
            return json([
                'msg' => '错误',
            ]);
        }
        if (!TypeModel::isExist($type)) {
            return json([
                'msg' => '错误',
            ]);
        }
        $uid = Token::getUid();
        $data = [
            'content' => $content,
            'number'  => $number,
            'type'    => $type,
            'subtype' => $subtype,
            'time'    => time(),
            'user'    => $user,
            'uid'     => $uid
        ];

        // 插入数据
        MoneyModel::insert($data);
        return json([
            'code'  => 0,
            'msg'   => '插入成功！',
        ]);
    }
}
